// 解密
var ProtocolType = require('ProtocolType');
var Byte = require('Byte');

module.exports = cc.Class({
    properties: {
        byte: null,
    },
    ctor(data){
        this.byte = new Byte(data);
    },

    readInt(){
        var b = this.byte.getUint8();
        if (b == ProtocolType.ArgTypeTrue) {
            return 1;
        } else if (b == ProtocolType.ArgTypeNull) {
            return 0;
        } else if (b == ProtocolType.ArgTypeIntByte1) {
            return this.byte.getUint8();
        } else if (b == ProtocolType.ArgTypeIntByte2) {
            return this.byte.getUint16();
        } else if (b == ProtocolType.ArgTypeIntByte3) {
            return this._getThree(this.byte);
        } else if (b == ProtocolType.ArgTypeIntByte4) {
            return this.byte.getInt32();
        } else {
            // todo 协议减4
            return b - 4;
        }
    },
    readBoolean(){
        var b = this.byte.getUint8();
        if (b == ProtocolType.ArgTypeTrue) {
            return true;
        } else if (b == ProtocolType.ArgTypeNull) {
            return false;
        } else {
            return null;
        }
    },
    readString(){
        var b = this.byte.getUint8();
        if (b == ProtocolType.ArgTypeString) {
            var len = this.readInt();
            var ret = this.byte.readUTFBytes(len);
            return ret;
        } else {
            return null;
        }
    },
    readStringArray(){
        var len = this.readInt();
        if (len == -1) {
            return null;
        }
        var a = [];
        for (var i = 0; i < len; i++) {
            a[i] = this.readString();
        }
        return a;
    },
    _getThree(in0){
        var ch1;
        var ch2;
        var ch3;

        // 大端排序,小端排序
        if (in0.endian == Byte.BIG_ENDIAN) {
            ch1 = in0.getUint8();
            ch2 = in0.getUint8();
            ch3 = in0.getUint8();
            return ((ch1 << 16) + (ch2 << 8) + (ch3 << 0));
        } else {
            ch1 = in0.getUint8();
            ch2 = in0.getUint8();
            ch3 = in0.getUint8();
            return ((ch1 << 0) + (ch2 << 8) + (ch3 << 16));
        }
    },
});
